<template>
  <div class='dashboard' style="min-width: 1880px;overflow:auto;">

    <DeptSelect @changeDept="changeDept"></DeptSelect>

    <!-- 左侧内容 start -->
    <div class="left-column flex-column flex-space-between overflow-auto both-100 " style="height: calc(100vh - 130px)">

      <DashboardCard title="报警统计" :operation="true" height="260px">
        <template #content>
          <div class='width-100'>
            <div class="box-title width-100 mt10">
              <CustomTitle title="今日报警数据总览" :isAutoMargin="false" :isLine="true" fontSet="font1" :BgIsNone="true"></CustomTitle>
            </div>
            <div class="flex">
              <div class="level">
                <LevelBox :level="level" />
              </div>
              <div class="con flex flex-1">
                <div class="div-block flex-1">
                  <p class="txt">风险报警总数</p>
                  <p class="num">{{ stattisticsTodayAlarmCount.total }}</p>
                </div>
                <div class="div-block flex-1">
                  <span class="block-btn color-red">已确认</span>
                  <div class="num">{{ stattisticsTodayAlarmCount.confirmCount }}</div>
                </div>
                <div class="div-block flex-1">
                  <span class="block-btn ">误报</span>
                  <div class="num">{{ stattisticsTodayAlarmCount.falseCount }}</div>
                </div>
              </div>
            </div>
            <div class="mt10">
              <DashboardProgress :min="stattisticsTodayAlarmCount.finishCount" :max="stattisticsTodayAlarmCount.todoCount" unit="处理"></DashboardProgress>
            </div>
          </div>
        </template>
      </DashboardCard>

      <DashboardCard title="预警报警趋势分析" :operation="true" height="250px">
        <template #operation>
          <el-select v-model="value" placeholder="请选择" @change="changeTime">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </template>
        <template #content>
          <div class="width-100 chart">
            <TrendAnalysis :height="180" :dataList="alarmTrend"></TrendAnalysis>
          </div>
        </template>
      </DashboardCard>

      <DashboardCard title="预警报警类型" :operation="true" height="240px">
        <template #content>
          <div class="width-100 chart">
            <SingleRing :height="180" :dataList="alarmTypeResult"></SingleRing>
          </div>
        </template>
      </DashboardCard>

      <DashboardCard title="预警报警级别" :operation="true">
        <template #content>
          <div class="width-100 chart">
            <div style="display: flex;width: 440px;height: 130px;">
              <LevelRing bgClass="level1" text="I级 重大" :total="urgencyResult.all" :curValue="urgencyResult.highCount"></LevelRing>
              <LevelRing bgClass="level2" text="II级 较大" :total="urgencyResult.all" :curValue="urgencyResult.middleCount"></LevelRing>
              <LevelRing bgClass="level3" text="III级 一般" :total="urgencyResult.all" :curValue="urgencyResult.lowCount"></LevelRing>
              <LevelRing bgClass="level4" text="IV级 低" :total="urgencyResult.all" :curValue="urgencyResult.lowestCount"></LevelRing>
            </div>
          </div>
        </template>
      </DashboardCard>
    </div>
    <!-- 左侧内容 end -->

    <!-- 中间内容 start -->
    <div class="center-column both-100 flex flex-column flex-space-between">
      <div class="center-column-map flex-1">
        <div class="map both-100" style="position: relative;">
          <LongyanMap ref="chart" width="100%" height="100%" @onClick="getAlarmDetails" :mapData="mapData"></LongyanMap>
          <Legends :legendData="legendData"></Legends>
        </div>
      </div>
      <div class="center-column-bottom">
        <DashboardCardBig title="预警报警级别" :operation="true">
          <template #content>
            <div class="width-100 flex " style="height: 285px;">
              <div class="left flex-1 ">
                <div class="box-content">
                  <div class="box-item flex" v-for="(item, index) in deviceTypeList" :key="index">
                    <div class="item-icon flex flex-bcenter">
                      <i class="iconfontShuzhi" :class="'icon-' + item.icon"></i>
                    </div>
                    <div class="item-content flex flex-column both-100">
                      <div class="item-title">{{ item.deviceTypeName }}</div>
                      <div class="item-content">{{ item.num }}</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="table" style="width: 500px;margin-top: 21px;">
                <el-table :data="deviceList" v-loading="deviceLoading" stripe class="per_table" :height="225" style="width: 100%;">
                  <el-table-column prop="deviceTypeName" label="设备类型"></el-table-column>
                  <el-table-column prop="deviceStatus" label="设备状态">
                    <template slot-scope="scope">
                      <dict-tag :options="dict.type.device_status" :value="scope.row.deviceStatus" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="deptName" label="所属项目" width="160"></el-table-column>
                  <!-- <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                      <div class="">
                        <span type="text" class="tag_primary" size="small" @click="handleDealwith(scope.row)">处理</span>
                      </div>
                    </template>
                  </el-table-column> -->
                </el-table>
                <!-- 分页 -->
                <Pagination v-show="total > 0" :total="total" :page.sync="deviceSearch.pageNum" :limit.sync="deviceSearch.pageSize" small layout="total, sizes, prev, next, jumper" @change="getListDeviceData"></Pagination>
                <!-- 分页over -->
              </div>
            </div>
          </template>
        </DashboardCardBig>
      </div>
    </div>
    <!-- 中间内容 end -->

    <!-- 右侧内容 start -->
    <div class="right-column flex-column flex-1 flex-space-between overflow-auto both-100" style="height: calc(100vh - 130px)">

      <DashboardCard title="AI智能识别" :operation="true" height="35%">
        <template #content>
          <div class="width-100 chart pt10">
            <RisingSun :optionData="AIData" :width="410" :height="200" bgPoition="2.8% 50%" :ringPoition="['25%', '50%']" :colors="['#309EFF', '#FF7734', '#D9E7FF', '#FFDA98', '#2AE8BD', '#8FABBF', '#F14545']"></RisingSun>
          </div>
        </template>
      </DashboardCard>

      <DashboardCard title="事件列表" :operation="true" height="calc(65% - 15px)">
        <template #content>
          <div class="both-100 pt10" :style="{ 'box-sizing': 'border-box' }">
            <!-- <span class="sign" @click="setAllToRead">全部标记为已读</span> -->
            <ListItem :dictMap="dict" :dataList="eventList" @dealwith="dealwith">
              <template v-slot:status="{ scope }">
                <div class="status-content" v-if="scope.alarmStatus == 0">
                  <span class="status-unusual-radius"></span>
                  <span class="status-unusual">待处理</span>
                </div>
                <div class="status-content" v-else-if="scope.alarmStatus == 5">
                  <span class="status-normal-radius"></span>
                  <span class="status-normal">已完成</span>
                </div>
                <div class="status-content" v-else>
                  <span class="status-warning-radius"></span>
                  <span class="status-warning">处理中</span>
                </div>
              </template>
            </ListItem>
          </div>
        </template>
      </DashboardCard>

    </div>
    <!-- 右侧内容 end -->
    
    <el-dialog title="报警处理" class="large_dialog" :visible.sync="dialogDetails" top="10px" append-to-body>
      <alarm-dialog :details="alarmDetails"></alarm-dialog>
    </el-dialog>
    
  </div>
</template>

<script>
import { mapState } from 'vuex'
import DashboardCard from '@/components/Dashboard/Card'
import DashboardCardBig from '@/components/Dashboard/CardBig'
import LongyanMap from '@/components/map/longyan.vue'
import LevelBox from '@/components/Dashboard/LevelBox'
import DashboardProgress from '@/components/Dashboard/Progress';
import TrendAnalysis from '@/views/dashboard/echarts/TrendAnalysis.vue'
import SingleRing from '@/views/dashboard/echarts/SingleRing.vue'
import LevelRing from '@/views/dashboard/echarts/LevelRing.vue'
import RisingSun from '@/views/dashboard/echarts/RisingSun.vue'
import DeptSelect from '@/components/Dashboard/DeptSelect'
import ListItem from '@/components/Dashboard/List/ListItem.vue'
import AlarmDialog from '@/views/alarm/components/AlarmDialog'
import Legends from '@/components/map/legends.vue'

import { statTodayAlarmCount, statAlarmInfo, statAlarmInfoByDeviceType, statAlarmInfoByAiType } from '@/api/alarm/bigScreen'
import { listDeviceData } from '@/api/system/device/management';
import { listAlarm } from '@/api'
import { EventBus } from '@/utils/eventbus'

import exampleImage from '@/assets/images/points/厨房AI智能分析摄像机.png';
import exampleImage_2 from '@/assets/images/points/电气火灾.png';

export default {
  dicts: ['alarm_urgency_status', 'device_status'],
  data() {
    return {
      // 预警处置图 报警相关信息搜索条件
      searchMap: {
        deptId: '',
        endTime: new this.$Date().Format('yyyy-MM-dd hh:mm:ss'),
        startTime: new this.$Date(new this.$Date().getFullYear(), 0, 1).Format('yyyy-MM-dd 00:00:00')
      },
      // 下拉框-时间-列表
      options: [{
        value: new this.$Date().addDays(- new this.$Date().getDay()).Format('yyyy-MM-dd 00:00:00') + ' ~ ' + new this.$Date().Format('yyyy-MM-dd hh:mm:ss'),
        label: '本周'
      }, {
        value: new this.$Date().addDays(-new Date().getDate() + 1).Format('yyyy-MM-dd 00:00:00') + ' ~ ' + new this.$Date().Format('yyyy-MM-dd hh:mm:ss'),
        label: '本月'
      }, {
        value: new this.$Date(new this.$Date().getFullYear(), 0, 1).Format('yyyy-MM-dd 00:00:00') + ' ~ ' + new this.$Date().Format('yyyy-MM-dd hh:mm:ss'),
        label: '本年'
      }],
      // 下拉框-时间-列表对应的值 默认本年
      value: new this.$Date(new this.$Date().getFullYear(), 0, 1).Format('yyyy-MM-dd 00:00:00') + ' ~ ' + new this.$Date().Format('yyyy-MM-dd hh:mm:ss'),
      level: 4,
      // 预警报警级别-设备类型列表
      deviceTypeList: [],
      // 设备列表
      deviceList: [],
      deviceLoading: false,
      // 今日报警统计
      stattisticsTodayAlarmCount: {
        // 误报
        "falseCount": 0,
        // 已确认
        "confirmCount": 0,
        // 已处理
        "finishCount": 0,
        // 待处理
        "todoCount": 0
      },
      // 事件列表
      eventList: [{
        level: "IV",
        name: "D1车间楼顶",
        alarmTypeName: "越界侦测",
        alarmTime: "2022-11-30 10:21:31",
        alarmStatus: "0",
        alarmImg: "@/assets/images/acreagebg.png"
      }],
      // 事件列表-弹窗-显隐
      dialogDetails: false,
      // 报警事件详情
      alarmDetails: {},
      // 预警报警趋势分析
      alarmTrend: [],
      // 预警报警类型
      alarmTypeResult: [],
      // 预警报警级别
      urgencyResult: {
        "all": 0,
        "lowestCount": 0,
        "middleCount": 0,
        "highCount": 0,
        "lowCount": 0
      },
      // ai报警类型统计数量列表
      AIData: [],
      // 设备列表搜索条件
      deviceSearch: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      mapData:[],
      legendData:{
        title: "图例",
        data: [{
          name: "报警",
          url: require('@/assets/images/legend/fengxianyuan.png')
        }]
      }
    };
  },
  computed: {
    ...mapState('config', ['inFilePrefix'])
  },
  watch: {},
  created() {

    this.getListAlarmDebounce = this.$utils.debounce(this.getListAlarm, 1000)

    
    EventBus.$on('onMessage', data => {
      data.latitude = data.projectPoint.lat
      data.longitude = data.projectPoint.lng
      data.name = data.categoryName
      data.img = exampleImage_2
      data.symbolSize = [28, 50]
      this.mapData = this.mapData.concat([data])
      this.$refs.chart.setOptions()

      // 刷新事件列表
      this.getListAlarmDebounce(this.searchMap.deptId)
    })
  },
  mounted() {

  },
  methods: {
    // 全部标记为已读
    setAllToRead() {

    },
    // 设备监控，处理
    handleDealwith() {

    },
    // 切换部门
    changeDept(deptId) {
      this.searchMap.deptId = deptId
      this.deviceSearch.deptId = deptId
      this.getStatTodayAlarmCount(deptId)
      this.getStatAlarmInfo()
      this.getStatAlarmInfoByDeviceType(deptId)
      this.getStatAlarmInfoByAiType(deptId)
      this.getListDeviceData()
      this.getListAlarm(deptId)
    },
    // 今日统计数据
    getStatTodayAlarmCount(deptId) {
      statTodayAlarmCount({ deptId }).then(res => {
        if (res && 200 == res.code) {
          this.stattisticsTodayAlarmCount = res.data
          this.stattisticsTodayAlarmCount.total = res.data.finishCount + res.data.todoCount
        }
      })
    },
    // 获取报警相关信息
    getStatAlarmInfo() {
      statAlarmInfo(this.searchMap).then(res => {
        if (res && 200 == res.code) {
          let data = res.data
          this.$nextTick(() => {

            // 预警报警趋势分析
            this.alarmTrend = data.alarmTrend
            // 预警报警类型
            this.alarmTypeResult = data.alarmTypeResult.map(item => {
              item.name = item.event_name
              item.value = item.num
              return item
            })
            // 预警报警级别
            let all = 0
            for (let p in data.urgencyResult) {
              let obj = data.urgencyResult
              all += obj[p]
              this.$set(this.urgencyResult, p, obj[p])
            }
            this.$set(this.urgencyResult, 'all', all)
          })
        }
      })
    },
    // 按设备类型统计报警数量
    getStatAlarmInfoByDeviceType(deptId) {
      statAlarmInfoByDeviceType({ deptId }).then(res => {
        if (res && 200 == res.code) {
          let icons = {
            '消防设备': 'xiaofangshebei',
            '安防设备': 'anfangshebei',
            '智能门禁': 'zhinengmenjin',
            '编码设备': 'yongdianjiance',
            '防雷设备': 'fangleijiance',
            '酒精探测设备': 'jiujingtance',
            '安防设备': 'anfangshebei',
            '烟雾探测': 'yanwutance',
            '其它设备': 'yongdianjiance'
          }
          this.deviceTypeList = res.data.map(item => {
            item.icon = icons[item.deviceTypeName]
            return item
          })
        }
      })
    },
    // 按ai报警类型统计数量
    getStatAlarmInfoByAiType(deptId) {
      statAlarmInfoByAiType({ deptId }).then(res => {
        if (res && 200 == res.code) {
          this.AIData = res.data.map(item => {
            item.name = item.eventName
            item.value = item.num
            return item
          })
        }
      })
    },
    // 获取设备列表
    getListDeviceData() {
      this.deviceLoading = true;
      listDeviceData(this.deviceSearch).then(res => {
        if (res && 200 === res.code) {
          this.deviceList = res.rows;
          this.total = res.total;
        }
        this.deviceLoading = false;
      });
    },
    // 获取告警列表
    getListAlarm(deptId){
      listAlarm({ deptId }).then(res => {
        if (res && 200 === res.code) {
          this.eventList = res.rows;
        }
      })
    },
    // 获取报警事件详情
    getAlarmDetails(data){
      this.dealwith(data)
    },
    // 本周，本月，本年切换
    changeTime(value) {
      let timeArr = value.split(' ~ ')
      this.searchMap.startTime = timeArr[0]
      this.searchMap.endTime = timeArr[1]
      this.getStatAlarmInfo()
    },
    // 报警事件详情
    dealwith(row){
      this.alarmDetails = row
      this.dialogDetails = true
    }
  },
  components: {
    DashboardCard,
    DashboardCardBig,
    LongyanMap,
    LevelBox,
    DashboardProgress,
    TrendAnalysis,
    SingleRing,
    LevelRing,
    RisingSun,
    DeptSelect,
    ListItem,
    AlarmDialog,
    Legends
  },
  beforeDestroy() {
    EventBus.$off('onMessage')
  },
}
</script>

<style lang='less' scoped>
.dashboard {
  display: grid;
  grid-template-columns: 440px auto 440px;
  grid-gap: 10px;
  height: 100vh;

  .left-column,
  .middle-column,
  .right-column {
    overflow: auto;
    height: calc(100vh - 140px);
  }

  .left-column {
    .level {
      width: 100px;
      height: 100px;
    }

    .con {
      text-align: center;
      padding-left: 10px;

      .num {
        font-size: 20px;
        margin-top: 15px;
      }

      .div-block:first-child {
        text-align: left;

        .txt {
          font-size: 14px;
          line-height: 40px;
        }

        .num {
          font-weight: 400;
          font-size: 36px;
        }
      }
    }

    .block-btn {
      line-height: 40px;
    }
  }
}

/deep/ .operation .el-input__inner {
  border: none !important;
  width: 100px;
  text-align: right;
}

.db-card-box {
  margin-top: 15px;
}

.db-card-box:first-child {
  margin-top: 0;
}

.sign {
  border: 1px solid @primary;
  color: @primary;
  background-color: fade(@primary, 20);
  padding: 3px 6px;
  cursor: pointer;
}

.block-btn {
  border: 1px solid fade(@primary, 40);
  color: @primary;
  background: fade(@primary, 10);
  padding: 0 5px;
  cursor: pointer;
}

.color-red {
  border: 1px solid fade(@processed, 40);
  color: @processed;
  background: fade(@processed, 10);
}

.color-correct {
  border: 1px solid fade(@complete, 40);
  color: @complete;
  background: fade(@complete, 10);
}

.box-content {
  height: 100%;
  overflow: auto;
  justify-content: center;
  align-items: center;
  gap: 10px;

  .box-item {
    width: calc(50% - 20px);
    justify-content: center;
    align-items: center;
    gap: 5px;
    float: left;
    margin: 10px;

    .item-icon {
      width: 49px;
      height: 49px;
      background: url("@/assets/images/dashboard/box3.png") no-repeat;
      background-size: 100%;

      .iconfontShuzhi {
        font-size: 22px;
        color: white;
      }
    }

    .item-content {
      flex: 1;

      .item-content {
        font-family: Oswald, Oswald;
        font-weight: 500;
        font-size: 20px;
        color: @primary;
        background: rgba(143, 171, 191, 0.1);
        // padding: 5px;
        box-sizing: border-box;
      }

      .item-title {
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        font-size: 14px;
        color: #d9e7ff;
        position: relative;

        &::before {
          content: "";
          position: absolute;
          top: 10px;
          bottom: 0;
          width: 100%;
          height: 6px;
          background: rgba(143, 171, 191, 0.1);
        }
      }
    }
  }
}
</style>